import axios from 'axios'
import {getToken} from "@/utils/auth";
import {Message} from "element-ui";
import Vue from "vue";


axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8';
axios.defaults.headers['clientid'] = '209ef407810e3856f40870a9f0e769d7';

// 创建axios实例
const service = axios.create({
    // axios中请求配置有baseURL选项，表示请求URL公共部分
    baseURL: 'http://localhost/dev-api',
    // 超时
    timeout: 50000
})
// 请求拦截器
service.interceptors.request.use(
    config => {
        const isToken = (config.headers || {}).isToken === false;

        if (getToken() && !isToken) {
            config.headers['Authorization'] = 'Bearer ' + getToken(); // 让每个请求携带自定义token 请根据实际情况自行修改
        }

        // FormData数据去请求头Content-Type
        if (config.data instanceof FormData) {
            delete config.headers['Content-Type'];
        }
        return config;
    },
    error => {
        Message.error({message: '连接不到服务器，请稍后再试', offset: 150});
        return Promise.reject(error);
    }
)
// 响应拦截器
service.interceptors.response.use(res=> {
    const code = res.data.code
    const msg = res.data.msg
    // 二进制数据则直接返回
    if (res.request.responseType === 'blob' || res.request.responseType === 'arraybuffer') {
        return res.data
    }
    if (code === 200) {
        return res.data
    }
    if (code === 500) {
        Vue.prototype.$notify({
            title: 'EasyCTBA',
            message: msg,
            type: 'error',
            duration: '2000',
            offset: 100
        });
        return Promise.reject(new Error(msg))
    }
    if (code === 401){
        //返回登录页
        window.location.href = "/login";
        return Promise.reject(new Error(msg))
    }
    else {
        return Promise.resolve('error')
    }
},
    error=>{
    return Promise.resolve(error.response);
});
export default service
